<?php
namespace App\Api;

use PhalApi\Api;
use App\Domain\Member as DomainMember;
use PhalApi\Exception\BadRequestException;

/**
 * 个人信息
 */
class Member extends Api {
    public function getRules() {
        return array(
            'index' => array(
                'code' => array('name' => 'code', 'require' => true, 'desc' => '微信端返回的参数值'),
            ),
            'addMmber' => array(
                'openid' => array('name' => 'openid', 'require' => true, 'desc' => '微信用户的openid'),
                'gender' => array('name' => 'gender', 'require' => true, 'desc' => '微信用户的性别'),
                'avatarUrl' => array('name' => 'avatarUrl', 'require' => true, 'desc' => '微信用户的头像'),
                'nickName' => array('name' => 'nickName', 'require' => true, 'desc' => '微信用户的昵称'),
            ),
        );
    }

    /**
     * 个人中心首页信息获取接口
     * @desc 获取个人账号信息
     * @return int user_id 用户id
     * @return string head_pic 用户头像
     * @return string nickname 用户昵称
     * @return string openid 用户openid
     */
    public function index() {
        $openid = \PhalApi\DI()->wechatmini->getOpenid( $this->code );
        if( !$openid ){
            throw new BadRequestException('openid获取失败！', 600);
        }
//        $openid = array();
//        $openid['openid'] = 'o38Yr5GBg4xZRtryg54oTqhTRBTg';
        $token = \PhalApi\DI()->wechatmini->getAccessToken();
        if( !$token ){
            throw new BadRequestException('token获取失败！', 600);
        }
        $domain = new DomainMember();
        $member_info = $domain -> getUserInfo( $openid['openid'] );
        if( empty($member_info) ){
            return $openid;
        }
        $member_info['nickname'] = base64_decode($member_info['nickname']);
        return $member_info;
    }

    /**
     * 个人中心首页添加用户信息接口
     * @desc 添加用户信息
     * @return string 判断code为200即可
     */
    public function addMmber() {
        $domain = new DomainMember();
        $wx_info = array();
        $wx_info['gender'] = $this->gender;
        $wx_info['avatarUrl'] = $this->avatarUrl;
        $wx_info['nickName'] = base64_encode($this->nickName);
        $member_info = $domain -> getUserInfo( $this->openid );
        if( $member_info['user_id'] ){
            return $member_info['user_id'];
        }
        $res = $domain -> insertUserInfo( $this->openid, $wx_info );
        if( !$res ){
            throw new BadRequestException('用户信息存储失败！', 600);
        }else{
            return 1;
        }
    }


}
